<template>
  <div class="zdypzdd">
    <div class="header">
      <div class="modelBox">
        <i class="modelIcon"></i>
        <a-tooltip>
          <template slot="title">
            {{ modelData.remarks || '暂无' }}
          </template>
          <span class="modelName">{{ modelData.modelName }}</span>
        </a-tooltip>
        <!-- <span class="modelName" title="违规签订大包合同">违规签订大包合同</span> -->
      </div>
      <step class="step" :edit="true" @del="delStep" @edit="getModelTemplateStepList" :currentNum="stepCurrentNum"
        :isCheck="isCheck" :list="stepList" @changeStep="changeStepVal"></step>
      <i v-if="!isCheck" class="addStepIcon" @click="addStep"></i>
    </div>

    <div class="content">
      <div class="contentL">
        <div class="contentTitle contentFlexTitle contentLTitleBorder">
          <div>
            <i class="contentTitleIcon"></i>选择数据表
          </div>
          <i class="contentTitleAddIcon" v-if="!isCheck" @click="modelDataVisible = true" title="添加数据表"></i>
        </div>
        <div class="contentTree contentLTreeBorder">
          <a-tree v-if="departTree.length > 0" :treeData="departTree" :load-data="onLoadData" draggable
            @dragstart="handledragstart($event)">
            <a-icon slot="switcherIcon" type="down" />
            <template slot="custom" slot-scope="{ title, ifMain }">
              <div class="treeNode">
                {{ title }}
                <span :class="{ 'treeNodeIsMain': ifMain == 1 }">{{ ifMain == 1 ? '主表' : '附表' }}</span>
              </div>
              <!-- <span class="">{{ ifMain == 1 ? '主表' : '附表' }}</span> -->
            </template>
          </a-tree>
          <div v-else>暂无数据</div>
        </div>
        <div class="contentTitle"><i class="contentTitleIcon"></i>临时指标库</div>
        <div class="contentTree">
          <a-tree v-if="targetTree.length > 0" :treeData="targetTree" draggable @dragstart="handledragstart($event)">
            <a-icon slot="switcherIcon" type="down" />
          </a-tree>
          <div v-else>暂无数据</div>
        </div>
      </div>
      <div class="contentC">
        <div class="contentCBox">
          <div class="contentTitle">
            <i class="contentTitleIcon"></i>
            公式配置
            <div v-if="!isCheck" class="contentCBtn contentCSaveBtn" @click="IndicatorDataSourceClear">清空</div>
          </div>
          <!-- <IndicatorTable :columns="columns1"></IndicatorTable> -->
          <IndicatorTable :formulaList="formulaList" :dataSource="IndicatorDataSource" :columns="columns1"
            :isCheck="isCheck" @DropHandler="DropHandler('IndicatorDataSource', 'cacheIndicatorDataSource')"
            @dropItemHandler="dropItemHandler" @Edit="(id, idx) => handleEdit('IndicatorDataSource', id, idx)"
            @DataChange="(id, value, col, idx) => handleDataChange('IndicatorDataSource', id, value, col, idx)"
            @SaveData="(id, idx) => handleSaveData('IndicatorDataSource', 'cacheIndicatorDataSource', id, idx)"
            @Delete="(id, idx) => handleDeleteRow('IndicatorDataSource', id, idx)"
            @CancelData="(id, idx) => handleCancelData('IndicatorDataSource', 'cacheIndicatorDataSource', id, idx)"
            @Up="(id, idx) => handleUp('IndicatorDataSource', id, idx)"
            @Down="(id, idx) => handleDown('IndicatorDataSource', id, idx)" />
        </div>
        <div class="contentCBox">
          <div class="contentTitle">
            <i class="contentTitleIcon"></i>
            输出指标配置
            <div v-if="!isCheck" class="contentCBtn contentCSaveBtn" @click="OutputDataSource = []">清空</div>
          </div>
          <OutputTable :dataSource="OutputDataSource" :columns="columns2" :isCheck="isCheck"
            @DropHandler="DropHandler('OutputDataSource', 'cacheOutputDataSource')"
            @Edit="(id, idx) => handleEdit('OutputDataSource', id, idx)"
            @DataChange="(id, value, col, idx) => handleDataChange('OutputDataSource', id, value, col, idx)"
            @SaveData="(id, idx) => handleSaveData('OutputDataSource', 'cacheOutputDataSource', id, idx)"
            @Delete="(id, idx) => handleDeleteRow('OutputDataSource', id, idx)"
            @CancelData="(id, idx) => handleCancelData('OutputDataSource', 'cacheOutputDataSource', id, idx)"
            @Up="(id, idx) => handleUp('OutputDataSource', id, idx)"
            @Down="(id, idx) => handleDown('OutputDataSource', id, idx)" />
        </div>
        <div class="contentCBtnBox" v-if="!isCheck">
          <div class="contentCBtn contentCSaveBtn" @click="saveStepModel()">保存</div>
          <div class="contentCBtn contentCNextBtn" @click="nextStepModel()">下一步</div>
          <div class="contentCBtn contentCShowBtn" @click="showStepModel()">预览</div>
          <div class="contentCBtn contentCExecuteBtn" @click="implement()">执行</div>
        </div>
      </div>
      <div class="contentR">
        <div class="contentTitle contentLTitleBorder"><i class="contentTitleIcon"></i>函数公式</div>
        <!-- <div class="contentSubTitle"><i class="contentSubTitleIcon"></i>常用函数公式</div>
        <div class="contentRSub">
          <a-button v-for="(item, index) in formulaList" :key="index"
           class="contentRSubItem"
           :draggable="true" :data-value="item.value"
            @dragstart="formulaDragstart($event)"
            @dragend="formulaDragend($event)">{{ item.title }}</a-button>
        </div> -->
        <div class="contentSubTitle"><i class="contentSubTitleIcon"></i>全部函数公式</div>
        <div class="contentRSub">
          <a-button v-for="(item, index) in formulaList" :key="index" class="contentRSubItem" :draggable="true"
            :data-value="item.id" @dragstart="formulaDragstart($event)" @dragend="formulaDragend($event)">{{ item.sign
            }}</a-button>
        </div>
      </div>
    </div>

    <a-modal title="新增步骤" :visible="stepVisible" :confirm-loading="confirmLoading" @ok="stepConfig"
      @cancel="stepCancel">
      <a-form-model ref="stepForm" :rules="modalRules" :model="modalForm">
        <a-form-model-item label="步骤名称" prop="stepName">
          <a-input v-model="modalForm.stepName" :maxLength="20" placeholder="请输入步骤名称" />
        </a-form-model-item>
        <a-form-model-item label="步骤说明" prop="stepDesc">
          <a-input v-model.number="modalForm.stepDesc" type="textarea" placeholder="请输入步骤说明" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <a-modal title="选择模型数据" :width="800" :visible="modelDataVisible" :confirm-loading="modelDataLoading"
      @ok="modelDataConfig" @cancel="modelDataCancel">
      <a-input-search v-model="modelDataForm.keyword" placeholder="请输入名称" style="width: 100%;margin-bottom: 10px;"
        @search="getTemplateCollectConfigTable" />
      <a-table bordered :columns="modelDataColumns" :data-source="modelDataTableData" rowKey="id"
        :row-selection="{ selectedRowKeys: modelDataRowKeys, onChange: modelDataChange }">
        <span slot="preview" slot-scope="text, record">
          <a-button size="small" @click="handlePreview(record)">预览</a-button>
        </span>
        <span slot="action" slot-scope="text, record">
          <a-checkbox :disabled="!modelDataRowKeys.includes(record.id)" @change="actionChange(record.id)"
            :checked="mainTable == record.id">主表</a-checkbox>
        </span>
      </a-table>
    </a-modal>

    <a-modal title="预览" :width="1200" :visible="previewVisible" :confirm-loading="previewLoading" :footer="false"
      @cancel="previewCancel">
      <a-card style="margin: 15px 0;border-radius: 20px;">
        <div class="table-page-search-wrapper">
          <a-form-model ref="ruleForm" :model="queryParam" :rules="rules" layout="inline"
            @keyup.enter.native="loadData">
            <a-row :gutter="24">
              <a-col :md="12" :sm="16">
                <a-form-model-item label="部门" prop="proId">
                  <a-tree-select v-model="queryParam.proId" style="width: 100%"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="proTreeData"
                    placeholder="请选择部门" treeNodeFilterProp="title" @change="proIdChange" @search="searchBy"
                    :showSearch="true"></a-tree-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="8" :sm="12">
                <a-form-model-item label="查询时段" prop="time">
                  <a-range-picker format="YYYY-MM-DD" value-format="YYYY-MM-DD" v-model="queryParam.Time"
                    @change="handleDatechange" />
                </a-form-model-item>
              </a-col>
              <a-col :md="4" :sm="4">
                <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                  <a-button type="primary" @click="loadData" icon="search">查询</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form-model>
        </div>
      </a-card>
      <a-table size="middle" bordered :columns="previewColumns" :data-source="previewTableData"
        :pagination="ipagination" @change="handleTableChange"></a-table>
    </a-modal>
  </div>
</template>

<script>
import { getAction, postAction, deleteAction } from '@/api/manage'
import step from './components/step.vue'
import IndicatorTable from './components/IndicatorTable.vue'
import OutputTable from './components/OutputTable.vue'
import { columns1, columns2, columns3 } from './columns'
import { queryMyDeptTreeByParentIds } from '@/api/api'
export default {
  name: 'zdypzdd',
  components: { step, IndicatorTable, OutputTable },
  data() {
    return {
      modelId: null,
      modelData: {},
      columns1: columns1(),
      columns2: columns2(),
      tempdata: {},
      IndicatorDataSource: [],
      cacheIndicatorDataSource: [],
      OutputDataSource: [],
      cacheOutputDataSource: [],
      formulaTempdata: null,
      confirmLoading: false,
      stepVisible: false,
      modalForm: {},
      modalRules: {
        stepName: [{ required: true, message: '请输入步骤名称', trigger: 'blur' }],
      },
      stepCurrentNum: null,
      stepList: [],
      departTree: [],
      targetTree: [],
      formulaList: [],
      // 选择模型左侧树数据
      modelDataVisible: false,
      modelDataLoading: false,
      modelDataSelVal: [],
      modelDataColumns: [
        {
          title: '序号',
          dataIndex: '序号',
          width: 70,
          align: 'center',
          customRender: (t, r, index) => {
            return parseInt(index) + 1
          }
        },
        {
          title: '名称',
          dataIndex: 'name'
        },
        { title: '预览', dataIndex: 'preview', align: 'center', width: 100, scopedSlots: { customRender: 'preview' }, },
        { title: '操作', dataIndex: 'action', align: 'center', width: 100, scopedSlots: { customRender: 'action' }, }
      ],
      modelDataForm: {},
      modelDataTableData: [],
      mainTable: null,
      modelDataRowKeys: [],
      queryParam: {},
      proDefaultTreeData: [],
      proTreeData: [],
      previewVisible: false,
      previewLoading: false,
      previewColumns: [],
      previewTableData: [],
      isCheck: false,
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      runJudge: false,
      url: {
        // 查询模型详情
        queryById: '/sjmx2/modelTemplateConfig/queryById',
        // 初始化全数据
        allConfig: '/sjmx2/modelTemplateConfig/allConfig',
        // 获取模型步骤
        getModelTemplateStepList: '/sjmx2/modelTemplateStep/queryList',
        // 添加模型步骤
        addModelTemplateStep: '/sjmx2/modelTemplateStep/add',
        // 保存并下一步(保存公式和输出指标信息)
        addData: '/sjmx2/modelTemplateStep/addData',
        // 查询函数列表
        getSignFunList: '/sjmx2/modelTemplateSignFunction/queryList',
        // 获取步骤下公式配置列表
        getTempFunByModelId: '/sjmx2/modelTemplateFunctionConfig/queryByModelId',
        // 获取步骤下输出指标列表
        getTempOutByModelId: '/sjmx2/modelTemplateOutIndex/queryByModelId',
        addField: '/sjmx2/modelTemplateCollectConfig/addField',
        // 获取可选数据表列表
        getTemplateCollectConfigTable: '/sjmx2/modelTemplateCollectConfig/querySelectTable',
        // 获取已选择的数据列表
        getTemplateCollectConfigList: '/sjmx2/modelTemplateCollectConfig/queryList',
        // 获取数据表下属数据
        querySelectTableField: '/sjmx2/modelTemplateCollectConfig/querySelectTableField',
        deleteStep: '/sjmx2/modelTemplateStep/delete',
        // 查询指定步骤的输出指标 表头
        queryTitle: '/sjmx2/modelTemplateOutIndex/queryTitle',
        // 预览
        runSql: '/sjmx2/modelTemplateRun/runData',
        searchBy: 'sys/sysDepart/searchBy',
      },
    }
  },
  created() {
    const { id } = this.$route.query;
    this.modelId = id;
    this.queryById();
    this.allConfig();
    this.getSignFunList();
    this.getTemplateCollectConfigTable();
    this.queryMyDeptTreeByParentIds();
  },
  watch: {
    $route: {
      handler: function (to, from) {
        this.isCheck = to.query.check || false

      },
      immediate: true,
    },
  },
  methods: {
    handlePreview(data) {
      let fileUrl = `${window._CONFIG['onlinePreviewFileURL']}/sys/common/download${data.path}`
      // let url = `${window._CONFIG['onlinePreviewDomainURL']}?url=${encodeURIComponent(fileUrl)}`
      let url = `${window._CONFIG['onlinePreviewDomainURL']}?url=${encodeURIComponent(Base64.encode(fileUrl))}`
      window.open(url, '_blank')
    },
    actionChange(e) {
      if (this.mainTable == e) {
        this.mainTable = null;
      } else {
        this.mainTable = e;
      }
    },
    searchBy(e) {
      console.log(this.proDefaultTreeData, 'this.proDefaultTreeData');
      if (!e) {
        this.proTreeData = this.proDefaultTreeData;
        return
      }
      getAction(this.url.searchBy + '?keyWord=' + e).then((res) => {
        if (res.code == 0) {
          this.$set(this, 'proTreeData', res.result)
        }
      })
    },
    previewCancel() {
      this.previewVisible = false;
      this.queryParam = {};
      this.previewColumns = [];
      this.previewTableData = [];
      this.ipagination = {
        current: 1,
        pageSize: 10,
        total: 0
      };
    },
    handleDatechange(e) {
      if (e & e.length) {
        this.$set(this.queryParam, 'startTime', e[0].format('YYYY-MM-DD'));
        this.$set(this.queryParam, 'endTime', e[1].format('YYYY-MM-DD'));
      } else {
        this.$set(this.queryParam, 'startTime', null);
        this.$set(this.queryParam, 'endTime', null);
      }
    },
    queryMyDeptTreeByParentIds() {
      queryMyDeptTreeByParentIds().then((res) => {
        if (res.code == 0) {
          this.proDefaultTreeData = res.result;
          this.proTreeData = res.result;
        }
      })
    },
    proIdChange(value, label) {
      this.$set(this.queryParam, 'proName', label[0]);
    },
    handleTableChange(pagination, filters, sorter) {
      // 分页、排序、筛选变化时触发
      // TODO 筛选
      this.ipagination = pagination
      this.loadData()
    },
    loadData() {
      if (this.runJudge) {
        this.$message.error('禁止重复点击,请稍后重试');
        return
      }
      this.runJudge = true;
      setTimeout(() => {
        this.runJudge = false;
      }, 2000)
      let params = {
        id: this.modelId,
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize,
        stepOrder: this.stepCurrentNum,
        ...this.queryParam
      }
      if (!this.queryParam.proId) {
        this.$message.error('请选择部门')
        return
      }
      postAction(this.url.runSql, params).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message)
          this.previewTableData = res.result.records;
          this.$set(this.ipagination, 'total', res.result.total);
        } else {
          this.$message.error(res.message)
        }
      })
    },
    showStepModel() {
      this.queryTitle();
      // this.loadData();
      this.previewVisible = true;
    },
    queryTitle() {
      postAction(this.url.queryTitle, { id: this.modelId, stepOrder: this.stepCurrentNum }).then((res) => {
        if (res.code == 200) {
          let columns = [{
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1
            }
          }];
          for (let item of res.result) {
            columns.push({
              title: item.fieldCnName,
              key: item.fieldEnName,
              dataIndex: item.fieldEnName,
              align: 'center',
            })
          }
          this.previewColumns = columns;
          console.log(this.previewColumns, 'this.previewColumns');
        }
      })
    },
    delStep(data) {
      deleteAction(this.url.deleteStep, { id: data.id }).then((res) => {
        if (res.code == 200) {
          this.$message.success('删除成功');
          for (let i = 0; i < this.targetTree.length; i++) {
            let item = this.targetTree[i];
            if (item.key == `A${data.stepOrder}`) {
              this.targetTree.splice(i, 1);
              break;
            }
          }
          if (data.stepOrder == this.stepCurrentNum) {
            this.stepCurrentNum = null;
          }
          this.getModelTemplateStepList();
        }
      })
    },
    implement() {
      this.$router.push('/zdypzbb/worker?id=' + this.modelId)
    },
    modelDataChange(e) {
      this.modelDataRowKeys = e;
      if (!this.modelDataRowKeys.includes(this.mainTable)) {
        this.mainTable = null;
      }
    },
    getTemplateCollectConfigList() {
      getAction(this.url.getTemplateCollectConfigList, { modelId: this.modelId }).then((res) => {
        if (res.code == 200) {
          this.departTree = res.result.map(item => {
            return {
              title: item.tableName,
              key: item.id,
              tableId: item.tableId,
              modelId: item.modelId,
              ifMain: item.ifMain,
              scopedSlots: { title: "custom" }
            }
          });
        }
      })
    },
    getTemplateCollectConfigTable() {
      getAction(this.url.getTemplateCollectConfigTable, this.modelDataForm).then((res) => {
        if (res.code == 200) {
          this.modelDataTableData = res.result;
        }
      })
    },
    modelDataConfig() {
      let that = this;
      if (!this.mainTable) {
        this.$confirm({
          title: '是否不选择主表?',
          onOk() {
            that.addField();
          },
          onCancel() {
          },
        });
      } else {
        this.addField();
      }
    },
    addField() {
      let params = {
        modelId: this.modelId,
        templateList: this.modelDataRowKeys.join(','),
        mainTable: this.mainTable,
      }
      postAction(this.url.addField, params).then((res) => {
        if (res.code == 200) {
          this.$message.success('修改数据表成功');
          if (this.mainTable) {
            this.$router.push(`/zdypzbb/sjzcgl?modelId=${this.modelId}`);
          } else {
            this.getTemplateCollectConfigList();
            this.modelDataCancel();
          }
        }
      })
    },
    modelDataCancel() {
      this.modelDataVisible = false;
      this.modelDataLoading = false;
      this.modelDataSelVal = [];
    },
    getTempFunByModelId(tempNumVal) {
      const params = {
        modelId: this.modelId,
        stepOrder: tempNumVal || this.stepCurrentNum,
      };
      getAction(this.url.getTempFunByModelId, params).then((res) => {
        if (res.code == 200) {
          for (let item of res.result) {
            item.jslj = JSON.parse(item.jslj);
            item.srcs = JSON.parse(item.srcs);
            item.zb = JSON.parse(item.zb);
          }
          if (tempNumVal) {
            let judge = true;
            let children = res.result.map(itm => {
              return {
                key: itm.id,
                title: itm.jxjg,
                jxjgmc: itm.jxjgmc,
              }
            });
            for (let i = 0; i < this.targetTree.length; i++) {
              let item = this.targetTree[i];
              if (item.key == `A${tempNumVal}`) {
                judge = false;
                this.$set(this.targetTree[i], 'children', children)
                break;
              }
            }
            if (judge && children.length) {
              this.targetTree.push({
                key: `A${tempNumVal}`,
                title: `${this.stepList.find(item => item.stepOrder == tempNumVal).stepName}步骤`,
                children
              });
            }
          } else {
            this.IndicatorDataSource = res.result;
          }
        }
      })
    },
    getTempOutByModelId() {
      const params = {
        modelId: this.modelId,
        stepOrder: this.stepCurrentNum,
      };
      getAction(this.url.getTempOutByModelId, params).then((res) => {
        if (res.code == 200) {
          this.OutputDataSource = res.result;
        }
      })
    },
    getSignFunList() {
      getAction(this.url.getSignFunList).then((res) => {
        if (res.code == 200) {
          this.formulaList = res.result;
        }
      })
    },
    queryById() {
      getAction(this.url.queryById, { id: this.modelId }).then((res) => {
        if (res.code == 200) {
          this.modelData = res.result;
        }
      })
    },
    // 初始化全数据
    allConfig() {
      getAction(this.url.allConfig, { id: this.modelId }).then((res) => {
        if (res.code == 200) {
          for (let item of res.result.function) {
            item.jslj = JSON.parse(item.jslj);
            item.srcs = JSON.parse(item.srcs);
            item.zb = JSON.parse(item.zb);
          }
          this.IndicatorDataSource = res.result.function;
          this.OutputDataSource = res.result.out;
          this.departTree = res.result.table.map(item => {
            return {
              title: item.tableName,
              key: item.id,
              tableId: item.tableId,
              modelId: item.modelId,
              ifMain: item.ifMain,
              scopedSlots: { title: "custom" }
            }
          });
          this.modelDataRowKeys = res.result.table.map(item => item.tableId);
          if (res.result.table.find(item => item.ifMain == 1)) {
            this.mainTable = res.result.table.find(item => item.ifMain == 1).tableId;
          }
          this.stepList = res.result.step;
          if (this.stepList.length) {
            this.stepCurrentNum = this.stepList[0].stepOrder;
          }
          let tempTree = [];
          for (let key in res.result.temp) {
            const data = res.result.temp[key];
            let children = [];
            for (let i = 0; i < data.length; i++) {
              const item = data[i];
              if (item.jxjg) {
                children.push({
                  key: item.id,
                  title: item.jxjg,
                  jxjgmc: item.jxjgmc,
                })
              }
            }
            tempTree.push({
              key: `A${key}`,
              title: `${res.result.step.find(item => item.stepOrder == data[0].stepOrder).stepName}步骤`,
              children
            });
          }
          this.targetTree = tempTree;
        }
      })
    },
    // 指标参数表 拖拽接收数据
    DropHandler(targetData, cacheData) {
      if (!this.stepList || !this.stepList.length) {
        this.$message.error('请先添加模型步骤')
        return
      }
      if (!this.tempdata || (!this.tempdata.id && !this.tempdata.jxjgmc)) {
        this.$message.error('请选择数据表数据')
        return
      }
      //  去重
      let result = this[targetData].find(item => item.id == this.tempdata.id)
      // if (!result && this.TreeSwitching) {
      if (targetData.indexOf('IndicatorDataSource') != -1) {
        if (this.tempdata.jxjgmc) {
          this[targetData].push({
            zb: {
              fieldName: this.tempdata.title,
              fieldTemp: this.tempdata.jxjgmc,
            }
          })
        } else {
          this[targetData].push({
            zb: {
              id: this.tempdata.id,
              fieldName: this.tempdata.title,
              fieldEnName: this.tempdata.enName,
              fieldType: this.tempdata.fieldType,
              sourceId: this.tempdata.sourceId,
              sourceTableName: this.tempdata.sourceTableName,
            }
          })
        }
      } else {
        if (this.tempdata.jxjgmc) {
          this[targetData].push({
            id: this.tempdata.id,
            funcId: this.tempdata.jxjgmc,
            fieldCnName: this.tempdata.title,
            fieldEnName: this.tempdata.jxjgmc,
          })
        } else {
          this[targetData].push({
            id: this.tempdata.id,
            fieldCnName: this.tempdata.title,
            fieldEnName: this.tempdata.enName,
            tableName: this.tempdata.sourceTableName,
          })
        }
      }
      this[cacheData] = [...this[targetData]]
      // } else if (result) {
      //   this.$message.warning('指标参数重复')
      // } else {
      //   this.$message.error('当前树形数据不可用')
      // }
      // 更改setps状态
      if (this[targetData].length > 0) {
        if (targetData.indexOf('IndicatorDataSource') != -1) {
          this.changeStep(1, true)
        } else {
          this.changeStep(2, true)
        }
      }
      this.changeStep(3, false)
      this.tempdata = {}
    },
    // 表格编辑部分
    handleEdit(targetData, id, idx) {
      this.changeStep(3, false)
      const newData = [...this[targetData]]
      const target = newData[idx];
      // const target = newData.find(item => id === item.id)
      if (target) {
        target.editable = true
        this[targetData] = newData
      }
      console.log(this[targetData])
    },
    handleDataChange(targetData, id, value, col, idx) {
      this.changeStep(3, false)
      let newData = [...this[targetData]]
      if (targetData == 'IndicatorDataSource') {
        newData = this.editIndicatorDataSourceData(newData, value, col, idx);
      } else {
        newData = this.editOutputDataSource(newData, value, col, idx);
      }
      this[targetData] = newData
      // const target = newData.find(item => id === item.id)
      // if (target) {
      // target[col] = value
      // }
    },
    editOutputDataSource(newData, value, col, idx) {
      const target = newData[idx];
      target[col] = value;
      return newData
    },
    editIndicatorDataSourceData(newData, value, col, idx) {
      const target = newData[idx];
      if (col == 'jxjg') {
        target[col] = value;
        if (!target['jxjgmc']) {
          target['jxjgmc'] = `A${this.stepCurrentNum}_${idx + 1}_${this.uuid(6, 10)}`;
        }
        this.setTempNewData(target);
      } else if (col == 'srcs') {
        target.srcs = {
          fieldValue: value
        };
      } else if (col == 'jslj') {
        for (let item of this.formulaList) {
          if (item.id == value) {
            target.jslj = {
              id: item.id,
              sign: item.sign,
              signParam: item.signParam
            }
            break;
          }
        }
      }
      return newData
    },
    setTempNewData(target) {
      let tempStepData = null;
      for (let item of this.targetTree) {
        if (item.key == `A${this.stepCurrentNum}`) {
          tempStepData = item;
          break;
        }
      }
      if (tempStepData) {
        // console.log(this.targetTree[this.stepCurrentNum - 1].children);
        let judge = true;
        for (let i = 0; i < tempStepData.children.length; i++) {
          let item = tempStepData.children[i];
          if (item.jxjgmc == target.jxjgmc) {
            judge = false;
            tempStepData.children.splice(i, 1);
            tempStepData.children.push({
              key: target.jxjgmc,
              title: target.jxjg,
              jxjgmc: target.jxjgmc,
            });
            break;
          }
        }
        if (judge) {
          tempStepData.children.push({
            key: target.jxjgmc,
            title: target.jxjg,
            jxjgmc: target.jxjgmc,
          })
        }
      } else {
        let stepCurrentName = null;
        for (let item of this.stepList) {
          if (item.stepOrder == this.stepCurrentNum) {
            stepCurrentName = item.stepName;
            break;
          }
        }
        this.targetTree.push({
          key: `A${this.stepCurrentNum}`,
          title: `${stepCurrentName}步骤`,
          children: [{
            key: target.jxjgmc,
            title: target.jxjg,
            jxjgmc: target.jxjgmc,
          }]
        });
      }
    },
    handleDeleteRow(targetData, id, idx) {
      this.changeStep(3, false)
      const dataSource = [...this[targetData]]
      // this[targetData] = dataSource.filter(item => item.id !== id)
      let target = dataSource[idx];
      this[targetData] = dataSource.filter((item, index) => index !== idx)
      // 更改setps状态
      if (targetData.indexOf('IndicatorDataSource') != -1) {
        this.changeStep(1, this[targetData].length > 0)
        let tempStepData = null;
        for (let item of this.targetTree) {
          if (item.key == `A${this.stepCurrentNum}`) {
            tempStepData = item;
            break;
          }
        }
        if (tempStepData) {
          for (let i = 0; i < tempStepData.children.length; i++) {
            let item = tempStepData.children[i];
            if (item.jxjgmc == target.jxjgmc) {
              tempStepData.children.splice(i, 1);
              break;
            }
          }
        }
      } else {
        this.changeStep(2, this[targetData].length > 0)
      }
    },
    handleSaveData(targetData, cacheData, id, idx) {
      this.changeStep(3, false)
      const newData = [...this[targetData]]
      const newCacheData = [...this[cacheData]]
      // const target = newData.find(item => id === item.id)
      const target = newData[idx]
      // const targetCache = newCacheData.find(item => id === item.id)
      const targetCache = {}
      // const targetCache = newCacheData[idx]
      if (target) {
        delete target.editable
        this[targetData] = newData
        console.log(newData);
        Object.assign(targetCache, target)
        this[cacheData] = newCacheData
      }
    },
    handleCancelData(targetData, cacheData, id, idx) {
      this.changeStep(3, false)
      const newData = [...this[targetData]]
      // const target = newData.find(item => id === item.id)
      const target = newData[idx]
      if (target) {
        Object.assign(
          target,
          this[cacheData][idx]
        )
        delete target.editable
        this[targetData] = newData
      }
    },
    handleUp(targetData, id, idx) {
      this.changeStep(3, false)
      let index = idx
      // let index = this[targetData].findIndex(item => item.id === id)
      if (index > 0) {
        this[targetData][index] = this[targetData].splice(index - 1, 1, this[targetData][index])[0]
      } else {
        this.$message.warning('当前已经为第一条')
      }
    },
    handleDown(targetData, id, idx) {
      this.changeStep(3, false)
      // let index = this[targetData].findIndex(item => item.id === id)
      let index = idx
      if (this[targetData].length - 1 > index) {
        this[targetData][index + 1] = this[targetData].splice(index, 1, this[targetData][index + 1])[0]
      } else {
        this.$message.warning('当前已经为最后一条')
      }
    },
    IndicatorDataSourceClear() {
      this.IndicatorDataSource = [];
      for (let i = 0; i < this.targetTree.length; i++) {
        let item = this.targetTree[i];
        if (item.key == `A${this.stepCurrentNum}`) {
          this.targetTree.splice(i, 1)
          break;
        }
      }
    },
    saveStepModel(switchJudge, idx) {
      for (let i = 0; i < this.IndicatorDataSource.length; i++) {
        let item = this.IndicatorDataSource[i];
        if (!item.srcs) {
          this.$message.error(`请填写第${i + 1}条公式的计算结果！`);
          return
        }
        this.$set(item, 'modelId', this.modelId);
        this.$set(item, 'functionOrder', i + 1);
        this.$set(item, 'stepOrder', this.stepCurrentNum);
      }
      for (let i = 0; i < this.OutputDataSource.length; i++) {
        let item = this.OutputDataSource[i];
        this.$set(item, 'modelId', this.modelId);
        this.$set(item, 'outOrder', i + 1);
        this.$set(item, 'stepOrder', this.stepCurrentNum);
      }
      const params = {
        stepOrder: this.stepCurrentNum, // 当前步骤数
        modelId: this.modelId,
        function: this.IndicatorDataSource,
        outIndex: this.OutputDataSource,
      }
      postAction(this.url.addData, params).then((res) => {
        if (res.code == 200) {
          this.$message.success('保存成功');
          if (switchJudge) {
            this.stepCurrentNum = idx;
            this.getTempFunByModelId();
            this.getTempOutByModelId();
          }
        } else {
          this.$message.error(res.message);
        }
      });
    },
    nextStepModel() {
      if (this.stepCurrentNum != this.stepList.length) {
        for (let i = 0; i < this.stepList.length; i++) {
          let item = this.stepList[i];
          if (item.stepOrder == this.stepCurrentNum) {
            this.changeStepVal(this.stepList[i + 1], this.stepList[i + 1].stepOrder);
            break;
          }
        }
      }
    },
    changeStep(index, flag) {
      setTimeout(() => {
        this.$emit('changStep', { index, flag })
      }, 0)
    },
    changeStepVal(data, idx) {
      const that = this;
      if (that.stepCurrentNum == idx) {
        return
      }
      if (this.isCheck) {
        that.getTempFunByModelId(that.stepCurrentNum);
        that.stepCurrentNum = idx;
        that.getTempFunByModelId();
        that.getTempOutByModelId();
      } else {
        that.$confirm({
          title: '是否保存数据?',
          onOk() {
            that.saveStepModel(true, idx);
          },
          onCancel() {
            that.getTempFunByModelId(that.stepCurrentNum);
            that.stepCurrentNum = idx;
            that.getTempFunByModelId();
            that.getTempOutByModelId();
          },
        });
      }

    },
    addStep() {
      this.stepVisible = true;
    },
    getModelTemplateStepList() {
      const params = {
        modelId: this.modelId
      }
      getAction(this.url.getModelTemplateStepList, params).then((res) => {
        if (res.code == 200) {
          this.stepList = res.result;
          if (this.stepCurrentNum == null && this.stepList.length) {
            this.stepCurrentNum = this.stepList[0].stepOrder;
            this.getTempFunByModelId();
            this.getTempOutByModelId();
          }
        }
      })
    },
    stepConfig() {
      this.$refs.stepForm.validate(valid => {
        if (valid) {
          const params = {
            modelId: this.modelId,
            ...this.modalForm,
          };
          postAction(this.url.addModelTemplateStep, params).then((res) => {
            if (res.code == 200) {
              this.$message.success('添加成功');
              this.getModelTemplateStepList();
              // this.stepList.push(this.modalForm);
              this.stepCancel();
            }
          })
        }
      });
    },
    stepCancel() {
      this.stepVisible = false;
      this.modalForm = {};
    },
    // 拖拽---逻辑
    handledragstart({ event, node }) {
      console.log('树节点 拖拽开始')
      let el = event.target
      setTimeout(() => {
        el.classList.add('a')
      })
      // 原始树--使用这个存储
      let { key, title, enName, fieldType, sourceId, sourceTableName, jxjgmc } =
        node.$options && node.$options.propsData.dataRef;
      // 中间存储变量
      this.tempdata = { id: key, title, enName, fieldType, sourceId, sourceTableName, jxjgmc }
      event.dataTransfer.effectAllowed = 'move'
    },
    // 函数公式拖拽
    formulaDragstart({ target }) {
      console.log('函数公式拖拽开始')
      let el = target
      setTimeout(() => {
        el.classList.add('a')
      })
      this.formulaTempdata = this.formulaList.find(item => item.id == target.dataset.value);
    },
    formulaDragend() {
      this.formulaTempdata = null;
    },
    dropItemHandler(type, idx) {
      if (type == 'jslj') {
        if (!this.formulaTempdata) {
          this.$message.error('请选择函数公式');
          return
        }
        this.$set(this.IndicatorDataSource[idx], type, {
          id: this.formulaTempdata.id,
          sign: this.formulaTempdata.sign,
          signParam: this.formulaTempdata.signParam
        });
        this.formulaTempdata = null;
      } else {
        if (!this.tempdata || !(this.tempdata.id || this.tempdata.jxjgmc)) {
          this.$message.error('请选择数据表数据');
          return
        }
        console.log(this.tempdata);
        if (this.tempdata.jxjgmc) {
          this.$set(this.IndicatorDataSource[idx], type, {
            fieldTemp: this.tempdata.jxjgmc,
            fieldName: this.tempdata.title,
          });
        } else {
          this.$set(this.IndicatorDataSource[idx], type, {
            id: this.tempdata.id,
            fieldName: this.tempdata.title,
            fieldEnName: this.tempdata.enName,
            fieldType: this.tempdata.fieldType,
            sourceId: this.tempdata.sourceId,
            sourceTableName: this.tempdata.sourceTableName,
          });
        }
        this.tempdata = null;
      }
    },
    // 获取左侧数据表 子集数据
    onLoadData(treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children) {
          resolve();
          return;
        }
        getAction(this.url.querySelectTableField, { tableId: treeNode.dataRef.tableId }).then((res) => {
          treeNode.dataRef.children = res.result.map(item => {
            return {
              isLeaf: true,
              key: item.id,
              title: item.cnName,
              enName: item.enName,
              fieldType: item.fieldType,
              sourceId: item.sourceId,
              sourceTableName: item.sourceTableName,
            }
          });
          this.departTree = [...this.departTree];
          resolve();
        })
      });
    },
    // 生成uuid 唯一标识
    uuid(len, radix) {
      let chars = '0123456789ABCDEFGHIJKLMNOPORSTUVWXYZabcdefghijkl';
      let uuid = [], i;
      radix = radix || chars.length;
      if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
      } else {
        let r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';
        for (i = 0; i < 36; i++) {
          if (!uuid[i]) {
            r = 0 | Math.random() * id;
            uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
          }
        }
      }
      return uuid.join('');
    }
  }
}
</script>

<style lang="less" scoped>
.zdypzdd {
  height: 100%;

  .header {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    background-color: #fff;
    border-radius: 20px;
    overflow: hidden;
    height: 80px;
  }

  .modelBox {
    padding: 20px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    width: 270px;
    height: 100%;
    background-color: #3154A4;
    overflow: hidden;
  }

  .modelIcon {
    margin-right: 15px;
    display: inline-block;
    width: 30px;
    height: 30px;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-image: url('../../../assets/new_modal/6.png');
  }

  .modelName {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;
    text-overflow: ellipsis;
    max-width: 80%;
    max-height: 100%;
    font-family: 'Arial Normal', 'Arial', sans-serif;
    font-weight: 400;
    font-style: normal;
    font-size: 20px;
    color: #FFFFFF;
    ;
    text-align: center;
    line-height: normal;
    letter-spacing: normal;
  }

  .step {
    box-sizing: border-box;
    padding: 0 10px 0 20px;
    width: calc(100% - 300px);
    height: 100%;
  }

  .addStepIcon {
    cursor: pointer;
    display: inline-block;
    width: 30px;
    height: 30px;
    background-image: url('../../../assets/zdypzbb/u22.svg');
    background-size: 100% 100%;
    background-repeat: no-repeat;
  }

  .content {
    height: calc(100% - 100px);
    margin-top: 20px;
    display: grid;
    grid-gap: 20px;
    grid-template-columns: 1fr 3fr 1fr;
  }

  .contentL {
    overflow-x: hidden;
    overflow-y: auto;
    box-sizing: border-box;
    border-radius: 20px;
    background-color: #fff;
  }

  .contentTitle {
    position: relative;
    padding: 15px 20px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    font-size: 18px;
    color: #3154A5;
    font-family: 'Arial Normal', 'Arial', sans-serif;
    font-weight: 400;
    font-style: normal;
    letter-spacing: normal;
    line-height: normal;
    border-bottom: 1px solid #E7E7E7;

    .contentTitleIcon {
      display: inline-block;
      margin-right: 8px;
      width: 4px;
      height: 18px;
      background-color: rgba(49, 84, 165, 1);
    }

    .contentCBtn {
      padding: 6px 16px;
      position: absolute;
      top: 50%;
      right: 0;
      transform: translateY(-50%);
    }
  }

  .contentFlexTitle {
    justify-content: space-between;
  }

  .contentTitleBorder {
    border-bottom: 1px solid #E7E7E7;
  }

  .contentTree {
    padding: 15px;

    ::v-deep .ant-tree-node-content-wrapper {
      position: relative;
      width: 100%;
    }

    .treeNode {
      &>span {
        padding: 1px 3px;
        border-radius: 4px;
        color: #3154A5;
        background-color: rgba(49, 84, 165, .1);
        border: 1px solid #3154A5;
        font-size: 12px;
        position: absolute;
        top: 50%;
        right: 20px;
        transform: translateY(-50%);
      }

      .treeNodeIsMain {
        color: rgba(255, 153, 12, 1);
        background-color: rgba(255, 153, 12, .1);
        border: 1px solid rgba(255, 153, 12, 1);
      }
    }
  }

  .contentTreeBorder {
    border-bottom: 1px solid #E7E7E7;
  }

  .contentC {
    overflow-x: hidden;
    overflow-y: auto;
  }

  .contentCBox {
    box-sizing: border-box;
    padding: 0 15px 15px 15px;
    border-radius: 20px;
    background-color: #fff;
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .contentCBtnBox {
    margin-bottom: 10px;
    text-align: center;
  }

  .contentCBtn {
    cursor: pointer;
    margin-right: 15px;
    display: inline-block;
    border-radius: 5px;
    padding: 8px 20px;
    font-size: 14px;
    color: #FFFFFF;
    font-family: 'Arial Normal', 'Arial', sans-serif;
    font-weight: 400;
    font-style: normal;
    letter-spacing: normal;
    text-align: center;
    line-height: normal;

    &:last-child {
      margin-right: 0;
    }
  }

  .contentCSaveBtn {
    background-color: #3154A4;
  }

  .contentCNextBtn {
    background-color: #5FEE7B;
  }

  .contentCShowBtn {
    background-color: #E1E3E4;
  }

  .contentCExecuteBtn {
    background-color: #F59A23;
  }

  .contentR {
    overflow-x: hidden;
    overflow-y: auto;
    box-sizing: border-box;
    padding: 15px;
    border-radius: 20px;
    background-color: #fff;
  }

  .contentSubTitle {
    padding: 15px 20px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    font-size: 14px;
    font-family: 'Arial Normal', 'Arial', sans-serif;
    font-weight: 400;
    font-style: normal;
    letter-spacing: normal;
    line-height: normal;

    .contentSubTitleIcon {
      display: inline-block;
      margin-right: 8px;
      width: 6px;
      height: 6px;
      border-radius: 50%;
      background-color: rgba(49, 84, 165, 1);
    }
  }

  .contentRSub {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 15px;
    padding: 0 15px;
  }

  .contentTitleAddIcon {
    cursor: pointer;
    display: inline-block;
    width: 20px;
    height: 20px;
    background-image: url('../../../assets/new_modal/add.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
  }
}
</style>